package com.demo.util.excel.utils;

import com.demo.util.excel.annotations.ExcelColumn;
import com.demo.util.excel.beans.ExcelColumnVO;
import com.demo.util.excel.enums.ExcelDataType;
import com.demo.util.lambda.beans.SFunction;
import com.demo.util.lambda.utils.LambdaUtil;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class LambdaExcelColumnUtil {

    public static  <FT, T> ExcelColumnVO<T> getFuncColumn(SFunction<FT, ?> func) {
        Field fieldInfo = null;
        try {
            fieldInfo = LambdaUtil.getSFuncAnnotation(func);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (fieldInfo == null) {
            return null;
        }
        return getFieldColumn(fieldInfo);
    }

    public static <T> ExcelColumnVO<T> getFieldColumn(Field fieldInfo) {
        ExcelColumn excelColumn = fieldInfo.getAnnotation(ExcelColumn.class);
        ExcelColumnVO<T> column = new ExcelColumnVO<>();
        String fieldName = fieldInfo.getName();
        column.setTitle(fieldName);
        column.setField(fieldName);
        if (excelColumn != null) {
            String title = excelColumn.value();
            if (!title.isEmpty()) {
                column.setTitle(title);
            }
            String field = excelColumn.field();
            if (!field.isEmpty()) {
                column.setField(field);
            }
            ExcelDataType dataType = excelColumn.dataType();
            column.setDataType(dataType);
            String headerStyle = excelColumn.headerStyle();
            if (!headerStyle.isEmpty()) {
                column.setHeaderStyle(item -> headerStyle);
            }
            String cellStyle = excelColumn.cellStyle();
            if (!cellStyle.isEmpty()) {
                column.setCellStyle(item -> cellStyle);
            }
        }
        return column;
    }

    public static  <FT, T> List<ExcelColumnVO<T>> getClassAllColumns(Class<FT> clazz) {
        return Arrays.stream(clazz.getDeclaredFields())
                .map(LambdaExcelColumnUtil::<T>getFieldColumn)
                .collect(Collectors.toList());
    }

}
